using System;

using Microsoft.SPOT;

using mfRCF.Core;
using mfRCF.Core.Extensions;

using mfXmlSerializer;

using mfLogger;

using OST.Shared.SharedTypes;
using OST.Persistence;
using OST.Shared;

namespace OST.Commands
{
    using Extensions;
    using OST.Motor;

    /// <summary>
    /// drives to motorto a specified stroke
    /// </summary>
    public class MotorDriveManualGETCommand : mfRcfCommand
    {
        #region CTOR

        public MotorDriveManualGETCommand(string httpPath)
            : base(httpPath, new mfGETMethod())
        {
        }

        #endregion

        #region Properties

        /// <summary>
        /// wrapper-property 4 logging
        /// </summary>
        private ILoggerAppender Logger
        {
            get
            {
                return mfLogger.mfLogger.Instance;
            }
        }

        #endregion

        #region mfRcfCommand
        public override void ExecuteCommand(mfIHttpContext httpContext)
        {
            try
            {
                if (!MotorProvider.Instance.HasInstance)
                    throw new OSTException("no motor instance found");

                if (!MotorProvider.Instance.MotorInstance.IsInitialized)
                    throw new OSTException("motor not initialized");

                //extract the position-parameter
                var parameters = httpContext.Request.RawUrl.ExtractUrlParameter();

                if (!parameters.Contains("position"))
                    throw new OSTException(GetType() + " no position parameter specified");

                var motorPosition = Convert.ToInt32(parameters["position"].ToString());
                Logger.Debug(GetType() + "position '" + motorPosition + "' extracted");

                //drive to target
                var motor = MotorProvider.Instance.MotorInstance;
                motor.Move2MotorPositionAsync(motorPosition);

                this.WriteHttpResponseOK(httpContext, "driving2 "+motorPosition+"mm");
            }
            catch (Exception ex)
            {
                this.WriteHttpResponseError(httpContext, ex);
            }
        }

        #endregion
    }
}
